package leetcode.code1449;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public String largestNumber(int[] cost, int target) {
		int[][] dp = new int[target + 1][10];
		for (int i = 1; i <= target; i++) {
			int[] cur = null;
			for (int j = 0; j < 9; j++) {
				int c = cost[j];
				if (i - c < 0 || dp[i - c] == null) {
					continue;
				}
				int[] tmp = dp[i - c].clone();
				tmp[j] += 1;
				tmp[9] += 1;
				cur = cmp(cur, tmp);
			}
			dp[i] = cur;
		}
		int[] max = dp[target];
		if (max == null) {
			return "0";
		}
		StringBuffer ans = new StringBuffer();
		for (int i = 8; i >= 0; i--) {
			if (max[i] != 0) {
				String cur = String.valueOf(i + 1);
				ans.append(cur.repeat(max[i]));
			}
		}
		return ans.toString();
	}

	private int[] cmp(int[] cur, int[] tmp) {
		if (cur == null) {
			return tmp;
		}
		if (cur[9] > tmp[9]) {
			return cur;
		}
		if (tmp[9] > cur[9]) {
			return tmp;
		}
		for (int i = 8; i >= 0; i--) {
			if (tmp[i] > cur[i]) {
				return tmp;
			}
		}
		return cur;
	}

	@Override
	public void debug4() {
		H.compare("7772", this.largestNumber(H.str2array3("[4,3,2,5,6,7,2,5,5]"), 9));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
